package myJs.user

import myJs.Implicits._
import myJs.Utils
import myJs.Utils._
import scala.scalajs.js.Dynamic.{global=>g}
import myJs.myPkg.{BootstrapWizardOptions, LayerOptions}
import myJs.myPkg.bootstrap.Bootstrap.default._
import myJs.myPkg.jquery._
import myJs.tool.Tool
import org.scalajs.dom._
import org.scalajs.dom.ext.Ajax
import shared.VarTool
import myJs.tool.Tool._

import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import scala.concurrent.{Future, Promise}
import scala.scalajs.js
import scala.scalajs.js.JSON
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}

/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("EmailChange")
object EmailChange {

  val count = 60
  val form1Id = "form1"

  @JSExport("init")
  def init = {
    bootStrapValidator
    refreshPersonInfo
    bootstrapWizard

  }

  def onNext: js.Function = (e: Event, a: js.Any, index: Int) => {
    val b = getBv
    if (b) {
      $("li", $("#form_wizard_1")).removeClass("done")
      $(s"#${Tool.wizardId}").find("li").mapElems(y => y).take(index).foreach { y =>
        $(y).addClass("done")
      }
    }
    b
  }

  def onTabShow: js.Function = (e: Event, a: js.Any, index: Int) => {
    val iNum = $(s"#${Tool.wizardId}").find("li").length
    val curI = index + 1
    val percent = (curI / iNum.toDouble * 100).toInt
    $("#form_wizard_1").find(".progress-bar").css("width", s"${percent}%")
    tabShow
  }

  def bootstrapWizard = {
    val options = BootstrapWizardOptions.onNext(onNext).nextSelector(".button-next").onTabShow(onTabShow).
      onTabClick(Tool.onTabClick)
    $("#form_wizard_1").bootstrapWizard(options)
  }

  def getBv1 = {
    val formId = form1Id
    val bv = $(s"#${formId}").bv
    bv.validate()
    val formB = bv.isValid()
    if (formB) {
      val url = g.jsRoutes.controllers.AppController.validCode().url.toString
      val formData = $(s"#${formId}").serialize()
      val ajaxSettings = JQueryAjaxSettings.url(s"${url}").async(false).`type`("post").data(formData).
        success { (data: js.Any, status: String, e: JQueryXHR) =>
          val rs = data.asInstanceOf[js.Dictionary[js.Any]]
          val valid = rs("valid").toB
          if (!valid) {
            bv.updateMessage("validCode", "blank", messages("ErrorInVerificationCode"))
            bv.updateStatus("validCode", "INVALID", "blank")
          }
          $(".myNext").dataValid(valid)
        }
      $.ajax(ajaxSettings)
    }
    formB && $(".myNext").dataValid
  }

  def getBv2 = {
    val formId = "form2"
    val bv = $(s"#${formId}").bv
    bv.validate()
    val formB = bv.isValid()
    if (formB) {
      val url = g.jsRoutes.controllers.UserController.validEmailCode().url.toString
      val formData = $(s"#${formId}").serialize()
      val ajaxSettings = JQueryAjaxSettings.url(s"${url}").async(false).`type`("post").data(formData).
        success { (data: js.Any, status: String, e: JQueryXHR) =>
          val rs = data.asInstanceOf[js.Dictionary[js.Any]]
          val valid = rs("valid").toB
          if (!valid) {
            bv.updateMessage("validCode", "blank", messages("ErrorInVerificationCode"))
            bv.updateStatus("validCode", "INVALID", "blank")
          }
          $(".myNext").dataValid(valid)
        }
      $.ajax(ajaxSettings)
    }
    formB &&  $(".myNext").dataValid
  }

  @JSExport("myRun")
  def myRun = {
    val inputName = "email"
    val url = g.jsRoutes.controllers.UserController.updateEmail().url.toString
    val email = Tool.getInputByName(inputName).myVal
    val dict = js.Dictionary("email" -> email)
    val data = JSON.stringify(dict)
    Ajax.post(url = s"${url}", data = data, headers = Map("Content-Type" -> "application/json")).map { xhr =>
    }
  }

  @JSExport("getBv")
  def getBv = {
    val tabId = $(".tab-pane.active").attr("id").get
    if (tabId == "tab2") {
      val b = getBv2
      if (b) {
        myRun
      }
      b
    } else if (tabId == "tab1") {
      val b = getBv1
      if (b) {
      }
      b
    } else true
  }

  def refreshHref(count: Int) = {
    Utils.mySetInterval(count, curCount => {
      $("#second").text(s"${curCount}")
    }, () => {
      val url = g.jsRoutes.controllers.UserController.securitySetBefore().url.toString
      window.location.href = s"${url}"
    }
    )
  }

  @JSExport("tabShow")
  def tabShow = {
    val tabId = $(".tab-pane.active").attr("id").get
    if (tabId == "tab3") {
      refreshHref(3)
    } else if (tabId == "tab2") {
      $(".refreshButton").text(messages("sendVerificationCode")).attr("disabled", false)
    }
  }

  def refreshTab1RemainTime(count: Int) = {
    Utils.mySetInterval(count, curCount => {
      $(s"#tab1 .refreshButton").text(s"${messages("resend")}（" + curCount + "）").attr("disabled", true)
    }, () => {
      $("#tab1 .refreshButton").text(messages("sendVerificationCode")).attr("disabled", false)
    }
    )
  }

  @JSExport("sendValidCode")
  def sendValidCode = {
    val phone = Tool.getInputByName("phone").myVal
    if (!phone.matches(VarTool.phoneRegexpStr)) {
      layer.msg(messages("pleaseEnterTheCorrectPhoneNumber"), LayerOptions.icon(5).time(3000))
      Tool.getInputByName("phone").focus()
    } else {
      refreshTab1RemainTime(count)
      val url = g.jsRoutes.controllers.AppController.sendValidCode().url.toString
      val dict = js.Dictionary("phone" -> phone)
      val data = JSON.stringify(dict)
      Ajax.post(url = s"${url}", data = data, headers = Map("Content-Type" -> "application/json")).map { xhr =>
        val rs = xhr.responseText.toJDJAn
        val valid = rs("valid").toB
        if (!valid) {
          layer.msg(rs.myGet("message"), LayerOptions.icon(5).time(3000))
        }
      }
    }
  }

  def refreshTab2RemainTime(count: Int) = {
    Utils.mySetInterval(count, curCount => {
      $("#tab2 .refreshButton").text(s"${messages("resend")}（" + curCount + "）").attr("disabled", true)
    }, () => {
      $("#tab2 .refreshButton").text(messages("sendVerificationCode")).attr("disabled", false)
    }
    )
  }

  @JSExport("sendEmailValidCode")
  def sendEmailValidCode = {
    val inputName = "email"
    val email = Tool.getInputByName(inputName).myVal
    if (!email.matches(VarTool.emailRegexpStr)) {
      layer.msg(messages("pleaseEnterTheCorrectEmail"), LayerOptions.icon(5).time(3000))
      Tool.getInputByName(inputName).focus()
    } else {
      refreshTab2RemainTime(count)
      val url = g.jsRoutes.controllers.UserController.sendEmailValidCode().url.toString
      val dict = js.Dictionary("email" -> email)
      val data = JSON.stringify(dict)
      Ajax.post(url = s"${url}", data = data, headers = Map("Content-Type" -> "application/json")).map { xhr =>
        val rs = xhr.responseText.toJDJAn
        val valid = rs("valid").toB
      }
    }
  }

  def refreshPersonInfo = {
    val url = g.jsRoutes.controllers.UserController.getUserById().url.toString
    Ajax.get(url = s"${url.noCache}&id=${getId}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val rs = xhr.responseText.toJDJAn.toMyJDS
      Tool.fillByNames(rs)
    }
  }

  def getId = {
    g.id.toString
  }

  def bootStrapValidator = {
    form1BootStrapValidator
    form2BootStrapValidator
  }

  def form1BootStrapValidator = {
    val maxNumber = Double.MaxValue
    val dict: js.Dictionary[js.Any] = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
        "validCode" ->{
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${messages("null")}"
              ),
              "blank" -> js.Dictionary()
            )
          )
        } ,
      )
    )
    $(s"#${form1Id}").bootstrapValidator(dict)
  }

  def form2BootStrapValidator = {
    val emailCheckUrl = g.jsRoutes.controllers.UserController.emailChangeCheck().url.toString
    val maxNumber = Double.MaxValue
    val dict: js.Dictionary[js.Any] = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
        "validCode" ->{
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${messages("null")}"
              ),
              "blank" -> js.Dictionary()
            )
          )
        } ,
        "email" ->{
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${messages("null")}"
              ),
              "emailAddress" -> js.Dictionary(
                "message" -> messages("illegal"),
              ),
              "remote" -> js.Dictionary(
                "message" ->messages("registered"),
                "url" -> emailCheckUrl,
                "delay" -> 1000,
                "type" -> "POST",
              ),
            )
          )
        } ,
      )
    )
    $(s"#form2").bootstrapValidator(dict)
  }


}
